package com.tepth.maintenancesystem.service;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;

import com.tepth.maintenancesystem.R;
import com.tepth.maintenancesystem.untils.FileUtils;

public class Update_App extends Service {
	private String app_name;
	private NotificationManager notificationManager;
	private Notification notification;
	private PendingIntent pendingIntent;
	private int notification_id = 0;
	private RemoteViews contentView;
	private static String down_url;
	private static final int TIMEOUT = 10 * 1000;// 超时
	private Context context;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		context=this;
		app_name = intent.getStringExtra("app_name");
		down_url = intent.getStringExtra("url");
		FileUtils.createFile(app_name);// 创建文件夹

		createNotification();// 创建通知

		startDownLoad();// 开启线程

		return super.onStartCommand(intent, flags, startId);
	}

	@SuppressWarnings("deprecation")
	public void createNotification() {
		notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		Notification.Builder builder = new Notification.Builder(context);//新建Notification.Builder对象
		builder.setContentTitle("开始下载");
		builder.setContentText("下载：0%");
		builder.setSmallIcon(R.mipmap.ic_launcher);
		builder.setContentIntent(pendingIntent);//执行intent

		/***
		 * 在这里我们用自定的view来显示Notification
		 */
		contentView = new RemoteViews(getPackageName(),
				R.layout.notification_item);
		contentView.setTextViewText(R.id.notificationTitle, this.getResources()
				.getString(R.string.app_name));
		contentView.setTextViewText(R.id.notificationPercent, "0%");
		contentView.setProgressBar(R.id.notificationProgress, 100, 0, false);
		notification = builder.getNotification();//将builder对象转换为普通的notification
		notification.contentView=contentView;
		notification.flags = Notification.FLAG_NO_CLEAR;//点击通知后通知不消失
		notificationManager.notify(notification_id, notification);//运行notification

	}

	public void startDownLoad() {
		new Thread(new Runnable() {
			public void run() {
				try {
					long downloadSize = downloadUpdateFile(down_url,
							FileUtils.updateFile.toString());
					if (downloadSize > 0) {
						// 下载成功
						handler.sendEmptyMessage(1);
					}

				} catch (Exception e) {
					e.printStackTrace();
					handler.sendEmptyMessage(2);
				}
			}
		}).start();
	}

	/***
	 * 下载文件
	 *
	 * @return
	 * @throws MalformedURLException
	 */
	public long downloadUpdateFile(String down_url, String file)
			throws Exception {
		int down_step = 5;// 提示step
		int totalSize;// 文件总大小
		int downloadCount = 0;// 已经下载好的大小
		int updateCount = 0;// 已经上传的文件大小
		InputStream inputStream;
		OutputStream outputStream;

		URL url = new URL(down_url);
		HttpURLConnection httpURLConnection = (HttpURLConnection) url
				.openConnection();
		httpURLConnection.setConnectTimeout(TIMEOUT);
		httpURLConnection.setReadTimeout(TIMEOUT);
		// 获取下载文件的size
		totalSize = httpURLConnection.getContentLength();
		if (httpURLConnection.getResponseCode() == 404) {
			throw new Exception("fail!");
		}
		inputStream = httpURLConnection.getInputStream();
		outputStream = new FileOutputStream(file, false);// 文件存在则覆盖掉
		byte buffer[] = new byte[1024];
		int readsize = 0;
		while ((readsize = inputStream.read(buffer)) != -1) {
			outputStream.write(buffer, 0, readsize);
			downloadCount += readsize;// 时时获取下载到的大小
			/**
			 * 每次增张5%
			 */
			if (updateCount == 0
					|| (downloadCount * 100 / totalSize - down_step) >= updateCount) {
				updateCount += down_step;
				// 改变通知栏
				// notification.setLatestEventInfo(this, "正在下载...", updateCount
				// + "%" + "", pendingIntent);
				contentView.setTextViewText(R.id.notificationPercent,
						updateCount + "%");
				contentView.setProgressBar(R.id.notificationProgress, 100,
						updateCount, false);
				// show_view
				notificationManager.notify(notification_id, notification);
			}
		}
		if (httpURLConnection != null) {
			httpURLConnection.disconnect();
		}
		inputStream.close();
		outputStream.close();
		return downloadCount;
	}

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@SuppressWarnings("deprecation")
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				// 下载完成，点击安装
				Uri uri = Uri.fromFile(FileUtils.updateFile);
				Intent intent = new Intent(Intent.ACTION_VIEW);

				intent.setDataAndType(uri,
						"application/vnd.android.package-archive");
				Notification.Builder builder = new Notification.Builder(context);//新建Notification.Builder对象
				builder.setContentTitle(app_name);
				builder.setTicker("下载成功");
				builder.setContentText("下载成功，点击安装");
				builder.setSmallIcon(R.mipmap.ic_launcher);
				builder.setContentIntent(pendingIntent);//执行intent
				notification = builder.getNotification();//将builder对象转换为普通的notification
				notification.flags = Notification.FLAG_AUTO_CANCEL;//点击通知后通知消失
				notificationManager.notify(notification_id, notification);
				notificationManager.cancel(notification_id);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setAction(Intent.ACTION_VIEW);
				startActivity(intent);
				stopSelf();// 停止服务
				break;
			case 2:
				Notification.Builder builder2 = new Notification.Builder(context);//新建Notification.Builder对象
				builder2.setContentTitle(app_name);
				builder2.setTicker("下载失败");
				builder2.setContentText("下载失败，请检查网络或存储空间");
				builder2.setSmallIcon(R.mipmap.ic_launcher);
				builder2.setContentIntent(pendingIntent);//执行intent
				notification = builder2.getNotification();//将builder对象转换为普通的notification
				notificationManager.notify(notification_id, notification);
				stopSelf();// 停止服务
				break;
			}
		}
	};

}
